<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class UserController extends Controller
{
    /**
     * 注册用户
     */
    public function register(Request $request)
    {
        $_user = Validator::make(
            $request->all(),
            [
                'name' => 'required|unique:users',
                'password' => 'required'
            ],
            [
                'name.required' => '用户名不能为空',
                'name.unique' => '用户名重复',
                'password.required' => '密码不能为空'
            ]
        )->validate();
        $_user["password"] = bcrypt($_user["password"]);
        $_user["rank"] = 1;
        $User = User::create($_user);
        if(!$User) $_result = response("注册失败",401);
        $_result = response($User);
        return $_result;
    }

    /**
     * 修改账号密码
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     * @throws \Illuminate\Validation\ValidationException
     */
    public function update(Request $request)
    {
        $_uid = auth()->id();
        $_user = Validator::make(
            $request->all(),
            [
                'name' => [
                    'required',
                    'min:3',
                    'max:20',
                    Rule::unique('users')->ignore($_uid)
                ],
                'password' => 'nullable|min:6|confirmed'
            ],
            [
                'name.required' => '请输入账号名',
                'name.min' => '账号长度在 3 到 20 个字符',
                'name.max' => '账号长度在 3 到 20 个字符',
                'name.unique' => '账号名已存在',
                'password.min' => '密码长度最少6个字符',
                'password.confirmed' => '两次密码不一致'
            ]
        )->validate();
        $_update_data = array(
            "name" => $_user['name']
        );
        if($_user['password']) {
            $_update_data['password'] = bcrypt($_user['password']);
        }
        $_result = User::where('id',$_uid)->update($_update_data);
        return $_result ? response('修改成功') : response('修改失败',401);
    }
}
